package com.since.data_structure.queue;

/**
 * Created by Sincerity on 2020/5/6.
 * 描述：环形
 */
public class CircularQueue {
    private int front;
    private int prev;
    private int maxSize;
    private int[] table;

    public CircularQueue(int maxSize) {
        this.maxSize = maxSize;
        table = new int[maxSize];
    }

    public int getSize() {
        if (table == null)
            throw new NullPointerException("队列没有实例化");
        return size();
    }

    public boolean isEmpty() {
        return prev == front;
    }

    public boolean isFull() {
        return (prev + 1) % maxSize == front;
    }

    public void add(int data) {
        if (isFull()) {
            System.out.println("队列已满.无法添加数据");
            return;
        }
        table[prev] = data; //直接赋值 并且赋值后需要把这个尾指针移动到下一个位置
        prev = (prev + 1) % maxSize;
    }

    public int getQueue() {
        if (isEmpty()) {
            throw new RuntimeException("队列是空的");
        }
        int value = table[front];
        front = (front + 1) % maxSize;
        return value;
    }

    public void show() {
        if (isEmpty()) {
            System.out.println("队列是空的");
            return;
        }
        for (int i = front; i < front + size(); i++) {
            System.out.printf("table[%d]=%d\n", i % maxSize, table[i % maxSize]);
        }
    }

    public int getHeader() {
        if (isEmpty()) {
            throw new RuntimeException("队列是空的");
        }
        return table[front];
    }

    //队列中的有效值 即队列的长度
    private int size() {
        return (prev + maxSize - front) % maxSize;
    }
}
